package cn.mrcode.smartFramework.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by zhuqiang on 2015/10/24 0024.
 * jdk 动态代理
 */
public class DynamicProxy implements InvocationHandler {
    private Object target;

    public DynamicProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("增加了前置处理");
        Object result = method.invoke(target, args); //转调目标的实际处理类
        System.out.println("增加了后置处理");
        return result;
    }

    public static void main(String[] args) {
        Hello hello = new Hello();
        DynamicProxy proxy = new DynamicProxy(hello);
        IHello o = (IHello) Proxy.newProxyInstance(
                hello.getClass().getClassLoader(), // 类加载器
                hello.getClass().getInterfaces(), //该类所实现的接口
                proxy);  // 代理实现类
        o.say("动态代理 简单使用");
    }
}

//
interface IHello{
    public void say(String msg);
}
class Hello implements IHello{
    public void say(String msg) {
        System.out.println(msg);
    }
}

// 静态代理
class HelloProxy implements IHello{
    private IHello iHello;

    public HelloProxy(IHello iHello) {
        this.iHello = iHello;
    }

    @Override
    public void say(String msg) {
        System.out.println("增加了前置处理");
        iHello.say(msg);
        System.out.println("增加了后置处理");
    }
}

class Demo{
    public static void main(String[] args) {
        HelloProxy proxy = new HelloProxy(new Hello());
        proxy.say("静态代理");
    }
}

